package mdb.com.vn.web.beans;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import mdb.com.vn.model.FixedDeposits;
import mdb.com.vn.model.ScratchCard;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.NumberUtils;
import mdb.com.vn.web.view.FDDataModel;


@ManagedBean(name = "fixedDepositsBean")
@ViewScoped
public class FixedDepositsBean implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<FixedDeposits> listOfFixedDeposits;
	private FixedDeposits fdSelected;
	private FDDataModel fdDataModel;
	private StreamedContent file;
	private boolean btnVisible;
	private boolean btnSaveVisible;
	
	
	
	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;
	
	@PostConstruct
	public void init() {
		listOfFixedDeposits = new ArrayList<FixedDeposits>();
		listOfFixedDeposits = mdbServices.getAllFixedDeposits();
		fdDataModel = new FDDataModel(listOfFixedDeposits);
	}
	
	public void createExcelFileByPoi() {
		Row row = null;
		Cell cell = null;
		try {

			Workbook wb = new HSSFWorkbook();
			HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
			HSSFFont fontHeader = (HSSFFont) wb.createFont();
			fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			styleHeader.setFont(fontHeader);
			Sheet sheet = wb.createSheet("TIET KIEM CO KY HAN");
			row = sheet.createRow((short) 0);
			List<String> columnNames = new ArrayList<String>();
		
			columnNames.add("Điểm giao dịch");
			columnNames.add("Ngày tạo");
			columnNames.add("Tên khách hàng");
			columnNames.add("Số CIF");
			columnNames.add("Số tài khoản");
			columnNames.add("Số tiền gửi");
			columnNames.add("Kỳ hạn (tháng)");
			columnNames.add("Lãi suất");
			columnNames.add("Thẻ cảm ơn");
			columnNames.add("20,000");
			columnNames.add("50,000");
			columnNames.add("100,000");
			columnNames.add("200,000");
			columnNames.add("500,000");
			columnNames.add("Tổng số thẻ cào");
			columnNames.add("Số tiền trúng thưởng");
			columnNames.add("Tổng số mã dự thưởng");
			columnNames.add("Khay mứt");
			columnNames.add("Áo thun");
			columnNames.add("Khay mứt thực nhận");
			columnNames.add("Áo thun thực nhận");
			for (int i = 0; i < columnNames.size(); i++) {
				cell = row.createCell(i);
				cell.setCellValue(columnNames.get(i));
				cell.setCellStyle(styleHeader);
			}
			int j = 1;
			List<Object[]> tabularData = new ArrayList<Object[]>();
			for (FixedDeposits fixedDeposit : listOfFixedDeposits) {
				List<ScratchCard> scratchCards = mdbServices
						.getListOfScratchCardByTranRef(fixedDeposit
								.getSavingbookNo());
				int number20k = 0;
				int number50k = 0;
				int number100k = 0;
				int number200k = 0;
				int number500k = 0;
				double totalSCAmount = 0;
				for (ScratchCard scratchCard : scratchCards) {
					double deno = scratchCard.getScDenomination();
					if (deno == NumberUtils.VND20000) {
						number20k = scratchCard.getQuantity();
						totalSCAmount += scratchCard.getQuantity() * NumberUtils.VND20000;
					}
					if (deno == NumberUtils.VND50000) {
						number50k = scratchCard.getQuantity();
						totalSCAmount += scratchCard.getQuantity() * NumberUtils.VND50000;
					}
					if (deno == NumberUtils.VND100000) {
						number100k = scratchCard.getQuantity();
						totalSCAmount += scratchCard.getQuantity() * NumberUtils.VND100000;
					}
					if (deno == NumberUtils.VND200000) {
						number200k = scratchCard.getQuantity();
						totalSCAmount += scratchCard.getQuantity() * NumberUtils.VND200000;
					}
					if (deno == NumberUtils.VND500000) {
						number500k = scratchCard.getQuantity();
						totalSCAmount += scratchCard.getQuantity() * NumberUtils.VND500000;
					}
				}
					tabularData.add(new Object[] {
							mdbServices.getCompanyNameByCode(fixedDeposit.getBranchCode()),
							fixedDeposit.getDateCreated(),
							fixedDeposit.getCustomerName(),
							fixedDeposit.getCustomerId(),
							fixedDeposit.getSavingbookNo(),
							fixedDeposit.getAmount(),
							fixedDeposit.getTerm(),
							fixedDeposit.getInterestRate(),
							fixedDeposit.getCheckGetThankSC(),
							number20k,
							number50k,
							number100k,
							number200k,
							number500k,
							fixedDeposit.getScCard(),
							totalSCAmount,
							fixedDeposit.getLuckyDraw(),
							fixedDeposit.getTrayGift(),
							fixedDeposit.getBagGift(),
							fixedDeposit.getTgiftReceived(),
							fixedDeposit.getBgiftReceived()});
			}
			
			HSSFCellStyle styleRow = (HSSFCellStyle) wb
					.createCellStyle();
			HSSFFont fontRow = (HSSFFont) wb.createFont();
			fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
			styleRow.setFont(fontRow);
			
			for (Object[] temp : tabularData) {
				row = sheet.createRow((short) j);
//				HSSFCellStyle styleRow = (HSSFCellStyle) wb
//						.createCellStyle();
				for (int k = 0; k < temp.length; k++) {	
//					HSSFFont fontRow = (HSSFFont) wb.createFont();
//					fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//					styleRow.setFont(fontRow);
					cell = row.createCell(k);
					cell.setCellValue(temp[k].toString());
					cell.setCellStyle(styleRow);
				}
				j++;
			}
			String excelFileName = "FIXED_DEPOSIT_REPORT.xls";
			FileOutputStream fos = new FileOutputStream(excelFileName);
			wb.write(fos);
			fos.flush();
			fos.close();
			InputStream stream = new BufferedInputStream(new FileInputStream(
					excelFileName));
			file = new DefaultStreamedContent(stream, "application/xls",
					excelFileName);
			setBtnVisible(true);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Xử lý xuất dữ liệu thành công",
							"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
		} catch (Exception e) {
			setBtnVisible(false);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Xử lý xuất dữ liệu thất bại",
							"Vui lòng liên hệ quản trị hệ thống."));
			e.printStackTrace();
		}
	}
	
	public void downloadPreventedFD() {
		file = null;
	}

	public FixedDeposits getFdSelected() {
		return fdSelected;
	}

	public void setFdSelected(FixedDeposits fdSelected) {
		this.fdSelected = fdSelected;
	}

	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	/**
	 * @return the fdDataModel
	 */
	public FDDataModel getFdDataModel() {
		return fdDataModel;
	}

	/**
	 * @return the listOfFixedDeposits
	 */
	public List<FixedDeposits> getListOfFixedDeposits() {
		return listOfFixedDeposits;
	}

	/**
	 * @param listOfFixedDeposits the listOfFixedDeposits to set
	 */
	public void setListOfFixedDeposits(List<FixedDeposits> listOfFixedDeposits) {
		this.listOfFixedDeposits = listOfFixedDeposits;
	}

	/**
	 * @return the btnVisible
	 */
	public boolean isBtnVisible() {
		return btnVisible;
	}

	/**
	 * @param btnVisible the btnVisible to set
	 */
	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	/**
	 * @return the btnSaveVisible
	 */
	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	/**
	 * @param btnSaveVisible the btnSaveVisible to set
	 */
	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	/**
	 * @return the file
	 */
	public StreamedContent getFile() {
		return file;
	}
	

}
